package com.maibow.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import com.maibow.util.Logger;

public class HttpUtil {
	private static Logger logger = Logger.getLogger(HttpUtil.class);
	public static String encoding;
	private static final HttpConnectionManager connectionManager;
	private static final HttpClient client;

	public HttpUtil() {
	}

	private static HttpConnectionManagerParams loadHttpConfFromFile() {
		Properties p = new Properties();
		try {
			p.load(HttpUtil.class.getResourceAsStream((new StringBuilder(String
					.valueOf(HttpUtil.class.getSimpleName().toLowerCase())))
					.append(".properties").toString()));
		} catch (IOException e) {
			logger.error(e);
		}
		encoding = p.getProperty("http.content.encoding");
		HttpConnectionManagerParams params = new HttpConnectionManagerParams();
		params.setConnectionTimeout(Integer.parseInt(p
				.getProperty("http.connection.timeout")));
		params.setSoTimeout(Integer.parseInt(p.getProperty("http.so.timeout")));
		params.setStaleCheckingEnabled(Boolean.parseBoolean(p
				.getProperty("http.stale.check.enabled")));
		params.setTcpNoDelay(Boolean.parseBoolean(p
				.getProperty("http.tcp.no.delay")));
		params.setDefaultMaxConnectionsPerHost(Integer.parseInt(p
				.getProperty("http.default.max.connections.per.host")));
		params.setMaxTotalConnections(Integer.parseInt(p
				.getProperty("http.max.total.connections")));
		params.setParameter("http.method.retry-handler",
				new DefaultHttpMethodRetryHandler(0, false));
		return params;
	}

	public static String post(String url, String encoding, String content) {
		byte resp[];
		try {
			resp = post(url, content.getBytes(encoding));
			if (resp == null)
				return null;
			return new String(resp, encoding);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e);
		}

		return null;
	}

	public static String post(String url, String content) {
		return post(url, encoding, content);
	}

	public static byte[] post(String url, byte content[]) {
		byte ret[];
		try {
			ret = post(url, ((RequestEntity) (new ByteArrayRequestEntity(
					content))));
			return ret;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e);
		}

		return null;
	}

	public static byte[] post(String url, RequestEntity requestEntity)
			throws Exception {
		PostMethod method;
		method = new PostMethod(url);
		method.addRequestHeader("Connection", "Keep-Alive");
		method.getParams().setCookiePolicy("ignoreCookies");
		method.getParams().setParameter("http.method.retry-handler",
				new DefaultHttpMethodRetryHandler(0, false));
		method.setRequestEntity(requestEntity);
		method.addRequestHeader("Content-Type",
				"application/x-www-form-urlencoded");
		int statusCode = client.executeMethod(method);
		if (statusCode != 200) {
			method.releaseConnection();
			return null;
		}
		byte abyte0[] = method.getResponseBody();
		method.releaseConnection();
		return abyte0;
	}

	static {
		HttpConnectionManagerParams params = loadHttpConfFromFile();
		connectionManager = new MultiThreadedHttpConnectionManager();
		connectionManager.setParams(params);
		client = new HttpClient(connectionManager);
	}
}